<template>
  <div class="maina">
    <div class="ttop">
      <div :style="{cursor: (lock? '':'pointer')}" :class="requestLoading? 'status_stop_Loading' : 'status_runing' "
           @click="ballClick"
           v-show="status === 1"></div>
      <div :style="{cursor: (lock? '':'pointer')}" :class="requestLoading? 'status_start_Loading' : 'status_stop' "
           @click="ballClick" v-show="status === 0"></div>
      <div class="erro"  v-show="status === 2"></div>
      <div class="talkErrot"  v-show="status === 3"></div>
      <div class="line" v-show="!ifLast"></div>
    </div>
    <div class="foots">
      <span>{{data.name}}</span>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'BallStatus',
    props: {
      data: {
        type: Object,
        default () {
          return {}
        }
      },
      statuses: {
        type: Array,
        default () {
          return []
        }
      },
      ifLast: {
        type: Boolean,
        default () {
          return false
        }
      },
      ifCtrl: {
        type: Boolean,
        default () {
          return true
        }
      },
        model: {
            type: String,
            default () {
                return '1'
            }
        }
    },
    mounted () {
      this.loadDevStatus(this.data.uuid)
    },
    data () {
      return {
        lock: false,
        requestLoading: false,
        statusTimer: [],
        status: 0
      }
    },
    methods: {
      ballClick () {
        this.$Modal.confirm({
          title: '操作确认',
          content: '<p>确认要执行远程操作设备指令吗？注意操作设备的次序问题。</p>',
          onOk: () => {
            this.doRequest()
          },
          onCancel: () => {
          }
        })
      },
      doSingleRequest () {
        if (!this.ifCtrl || this.lock) {
          return
        }
        this.$emit('lock-other-sons')
        this.doRequest().then(resp => {
            this.$Notice.info({
              title: '提示',
              desc: resp.msg
            })
        }).finally(() => {
          this.$emit('release-all-sons')
        })
      },
      doRequest () {
          // 发送请求到服务器 这里占用延时
        this.requestLoading = true
        this.$emit('dot-use-btn')
        // 发送请求
        let qq = {devId: this.data.devId, cmd: this.data.cmd[this.status], param: ''}
        window.myapi.do_post('iot/dev/cmdById', qq)
        // 轮训状态
        this.startTimerToGetStatus()
        // 记录当前状态
        let curStatus = this.status
        // 记录 请求状态的时间，超过一分钟超时
        let runTimeRecord = 0
        // 通过状态判断 返回最终的 启停结果
        return new Promise((resolve, reject) => {
          this.statusTimer.push(setInterval(() => {
            runTimeRecord++
            // 请求同步时长，超过则返回 操作超时
            if (runTimeRecord === 100) {
              // 停止定时器
              this.statusTimer.forEach(item => window.clearInterval(item))
              resolve({
                status: 2,
                msg: this.data.name + '100s操作超时'
              })
              this.requestLoading = false
              this.$emit('do-use-btn')
              return
            }
            if (curStatus !== this.status) {
              // 停止定时器
              this.statusTimer.forEach(item => window.clearInterval(item))
              resolve({
                status: 1,
                msg: this.data.name + '操作成功'
              })
              this.requestLoading = false
              this.$emit('do-use-btn')
            }
          }, 1000))
        })
      },
      startTimerToGetStatus () {
        this.statusTimer.push(setInterval(() => {
            this.loadDevStatus(this.data.uuid)
        }, 2000))
      },
        loadDevStatus (uuid) {
            window.myapi.do_post('iot/dev/sysReal', { uuid: uuid }).then(resp => {
                if (resp.status === 200 && resp.data.status === 200) {
                    this.handleStatus(resp.data.data)
                }
            }).finally(() => {})
        },
        handleStatus (hel) {
          let errotItem = hel.find(item => item.keyName === '故障状态')
          let statusItem = hel.find(item => item.keyName === '运行状态')
          // todo 水泵状态？
            if (errotItem && errotItem.value === 1) {
                this.status = 2
            } else {
                if (statusItem) {
                    if (statusItem.value === 0 || statusItem.value === 1 ) {
                        this.status = statusItem.value
                    } else {
                        this.status = 3
                        // 只要有一个错误，不能用 一键操作
                        this.$emit('dot-use-btn')
                    }
                } else {
                    let statusItem2 = hel.find(item => item.keyName === '开到位')
                    if (statusItem2) {
                      if (statusItem2.value === 0 || statusItem2.value === 1) {
                        this.status = statusItem2.value
                      } else {
                        this.status = 3
                        // 只要有一个错误，不能用 一键操作
                        this.$emit('dot-use-btn')
                      }
                    }
                }
            }
        },
      fatherCtrl (cmd) {
        if (this.status === 0 && cmd === 1) {
          // 一键开启 命令
          return new Promise((resolve, reject) => {
            this.doRequest().then(resp => {
              resolve(resp)
            })
          })
        } else if (this.status === 1 && cmd === 0) {
          // 一键关闭 命令
          return new Promise((resolve, reject) => {
            this.doRequest().then(resp => {
              resolve(resp)
            })
          })
        } else if (this.status === 1 && cmd === 1) {
          // 一键启动命令 且 设备已经处于 开启状态
          return new Promise((resolve, reject) => {
            resolve({
              status: 1,
              msg: this.data.name + '已处于开启状态'
            })
          })
        } else if (this.status === 0 && cmd === 0) {
          // 一键关闭 命令 且 设备已经处于关闭状态
          return new Promise((resolve, reject) => {
            resolve({
              status: 1,
              msg: this.data.name + '已处于关闭状态'
            })
          })
        } else {
          return new Promise((resolve, reject) => {
              resolve({
                status: 2,
                msg: '无法处理'
              })
          })
        }
      }
    },
      watch: {
          data (newOne, oldOne) {
              // 请求数据
              if (newOne.uuid) {
                this.loadDevStatus(newOne.uuid)
              }
          }
      },
    beforeDestroy: function () {
      this.statusTimer.forEach(item => window.clearInterval(item))
    }
  }
</script>

<style scoped>
  .maina{
    text-align: left;
    width: 100%;
  }
  .foots{
    margin-top: 3px;
    font-size: 14px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .ttop{
    display: inline-flex;
    width: 100%;
  }
  .status_runing {
    width: 44px;
    height: 44px;
    border-radius: 22px;
    margin: 0 auto;
    background: #0bff58;
    float: left;
  }
  .status_stop_Loading{
    position: relative;
    display: block;
    border-radius: 50%;
    background-color: #a9aaab;
    margin: 0 auto;
    width: 44px;
    height: 44px;
    animation: ani-spin-bounce 1s 0s ease-in-out infinite
  }

  .status_stop {
    width: 44px;
    height: 44px;
    border-radius: 22px;
    margin: 0 auto;
    background: #edeef0;
    float: left;
  }
  .status_start_Loading {
    position: relative;
    display: block;
    border-radius: 50%;
    background-color: #0bff58;
    margin: 0 auto;
    width: 44px;
    height: 44px;
    animation: ani-spin-bounce 1s 0s ease-in-out infinite
  }
  .line {
    float: left;
    height: 3px;
    background: #0bff58;
    margin-top: 25px;
    margin-left: 20px;
    border-radius: 1.5px;
  }

  .erro{
      width: 44px;
      height: 44px;
      border-radius: 22px;
      margin-left: 15px;
      background: #f36a5a;
      float: left;
  }
  .talkErrot{
      width: 44px;
      height: 44px;
      border-radius: 22px;
      margin-left: 15px;
      background: #f36a5a;
      float: left;
  }
  /*2k: 2560x1440*/
  @media screen and (min-width: 1921px) {
    .line {
      width: 75%;
    }
  }

  /* 1080: 1920*1080 */
  @media screen and (max-width: 1920px)  and (min-width: 1601px) {
    .line {
      width: 67%;
    }
  }

  /* 1600: 1600*900  */
  @media screen and (max-width: 1600px) and (min-width: 1367px) {
    .line {
      width: 60%;
    }
  }

  /* 1366: 1366*678 rr*/
  @media screen and (max-width: 1366px) {
    .line {
      width: 50%;
    }
  }
</style>
